package com.medicine.interceptor;

import com.medicine.common.utils.JsonUtil;
import com.medicine.utils.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bo.chen
 *
 */
public class LogerInterceptor extends BaseController implements HandlerInterceptor {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 请求controller之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
		String uri = getUri(req);
		String paramsJson = getParams(req);
		String tocken = req.getParameter("tocken");
		logger.info(uri);
		return true;
	}

	/**
	 * 请求controller之后，渲染ModelAndView之前执行
	 */
	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView modelAndView)
			throws Exception {
	}

	/**
	 * 渲染ModelAndView之后执行
	 */
	@Override
	public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex)
			throws Exception {
	}
	
	/**
	 * 获取请求的uri
	 * 
	 * @param req
	 * @return
	 */
	protected String getUri(HttpServletRequest req){
		return req.getServletPath();
	}
	
	/**
	 * 获取参数
	 * 
	 * @param req	HttpServletRequest对象
	 * @return
	 *	返回参数json格式数据
	 */
	protected String getParams(HttpServletRequest req){
		Map<String,String> paramMap = new HashMap<>();
		Enumeration<String> em = request.getParameterNames();
		while (em.hasMoreElements()) {
		    String name = (String) em.nextElement();
		    String value = req.getParameter(name);
		    if(name != null)
		    	paramMap.put(name, value);
		}
		return JsonUtil.bean2Json(paramMap);
	}
}

